<!--
 * @Author: liangzhuo liangzhuo@chzu.com
 * @Date: 2022-10-23 15:38:16
 * @LastEditors: liangzhuo liangzhuo@chzu.com
 * @LastEditTime: 2022-10-23 16:06:11
 * @FilePath: \hongxinUi\src\components\exam\examFileUpload.vue
 * @Description: 试题图片上传
-->
<template>
  <div>
    <el-form-item label="活动图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="upload"
            :before-upload="ImgBeforeAvatarUpload"
            :key="keyVal"
          >
            <img
              v-if="url + form.bucketName + '/' + form.fileName"
              :src="url + form.bucketName + '/' + form.fileName"
              style="width: 100px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
  </div>
</template>

<script>
import global from "@/global/global.js";
import { addFile } from "@/api/uploadFile/file";
export default {
  name: 'HongxinUiExamFileUpload',
  props: {
    form: {
      type : Object,
      default: {}
    }
  },
  data() {
    return {
      // 对话框的左边距
      formLabelWidth: "120px",
      // 封装图片的ip
      url: global.baseUrl,
      keyVal: 0,
    };
  },

  mounted() {
    
  },

  methods: {
    // 上传图片时接收到file对象并调用添加图片的接口
    upload(f) {
      // 1. 获取表单数据   formData 表单数据
      let formData = new FormData();
      formData.append("file", f.file);
      // 2. 发起请求
      addFile(formData).then((res) => {
        // 3. 请求成功之后  图片回显
        this.form.imgId = res.data.imgId;
        this.form.bucketName = res.data.bucketName;
        this.form.fileName = res.data.fileName;
        // 给父组件传值
        this.$emit("getChildrenForm", this.form)
        // 将对话框中的key的值+1，使模板重新编译从而使图片显示出来
        this.keyVal++;
      });
    },
    //上传前校验图片规则
    ImgBeforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 和 Png 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>

</style>